package cn.lsp.sharkmall.controller;

import cn.lsp.sharkmall.common.Constants;
import cn.lsp.sharkmall.common.ServiceResultEnum;
import cn.lsp.sharkmall.config.annotation.TokenToAdminUser;
import cn.lsp.sharkmall.pojo.dto.AdminAddNewDTO;
import cn.lsp.sharkmall.pojo.dto.AdminLoginDTO;
import cn.lsp.sharkmall.pojo.dto.UpdateAdminNameDTO;
import cn.lsp.sharkmall.pojo.dto.UpdateAdminPasswordDTO;
import cn.lsp.sharkmall.pojo.entity.AdminUser;
import cn.lsp.sharkmall.pojo.entity.AdminUserToken;
import cn.lsp.sharkmall.service.IAdminUserService;
import cn.lsp.sharkmall.util.PageQueryUtil;
import cn.lsp.sharkmall.util.PageResult;
import cn.lsp.sharkmall.util.Result;
import cn.lsp.sharkmall.util.ResultGenerator;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.hibernate.validator.constraints.Range;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.lsp.sharkmall.util.JsonResult;
import springfox.documentation.annotations.ApiIgnore;
import cn.lsp.sharkmall.pojo.vo.AdminVO;

/**
 * @Description:
 * @Author: sweeterjava@163.com
 * @Date: 2023/2/13
 * @Time: 02:15
 */

@RestController
@Api(value = "v1", tags = "8-0.后台管理系统管理员模块接口")
@RequestMapping("/manage-api/v1")
public class AdminManageUserController {
    @Resource
    private IAdminUserService adminUserService;

    private static final Logger logger = LoggerFactory.getLogger(AdminManageUserController.class);

    @RequestMapping(value = "/adminUser/login", method = RequestMethod.POST)
    public Result<String> login(@RequestBody @Valid AdminLoginDTO adminLoginDTO) {
        String loginResult = adminUserService.login(adminLoginDTO.getUserName(), adminLoginDTO.getPasswordMd5());
        logger.info("manage login api,adminName={},loginResult={}", adminLoginDTO.getUserName(), loginResult);

        //登录成功
        if (StringUtils.hasText(loginResult) && loginResult.length() == Constants.TOKEN_LENGTH) {
            Result result = ResultGenerator.genSuccessResult();
            result.setData(loginResult);
            return result;
        }
        //登录失败
        return ResultGenerator.genFailResult(loginResult);
    }

    @RequestMapping(value = "/adminUser/profile", method = RequestMethod.GET)
    public Result profile(@TokenToAdminUser AdminUserToken adminUser) {
        logger.info("adminUser:{}", adminUser.toString());
        AdminUser adminUserEntity = adminUserService.getUserDetailById(adminUser.getAdminUserId());
        if (adminUserEntity != null) {
            adminUserEntity.setLoginPassword("******");
            Result result = ResultGenerator.genSuccessResult();
            result.setData(adminUserEntity);
            return result;
        }
        return ResultGenerator.genFailResult(ServiceResultEnum.DATA_NOT_EXIST.getResult());
    }

    @RequestMapping(value = "/adminUser/password", method = RequestMethod.PUT)
    public Result passwordUpdate(@RequestBody @Valid UpdateAdminPasswordDTO adminPasswordParam,
                                 @TokenToAdminUser AdminUserToken adminUser) {
        logger.info("adminUser:{}", adminUser.toString());
        if (adminUserService.updatePassword(adminUser.getAdminUserId(),
                adminPasswordParam.getOriginalPassword(),
                adminPasswordParam.getNewPassword())) {
            return ResultGenerator.genSuccessResult();
        } else {
            return ResultGenerator.genFailResult(ServiceResultEnum.DB_ERROR.getResult());
        }
    }

    @RequestMapping(value = "/adminUser/name", method = RequestMethod.PUT)
    public Result nameUpdate(@RequestBody @Valid UpdateAdminNameDTO adminNameParam,
                             @TokenToAdminUser AdminUserToken adminUser) {
        logger.info("adminUser:{}", adminUser.toString());
        if (adminUserService.updateName(adminUser.getAdminUserId(),
                adminNameParam.getLoginUserName(),
                adminNameParam.getNickName())) {
            return ResultGenerator.genSuccessResult();
        } else {
            return ResultGenerator.genFailResult(ServiceResultEnum.DB_ERROR.getResult());
        }
    }

    @RequestMapping(value = "/logout", method = RequestMethod.DELETE)
    public Result logout(@TokenToAdminUser AdminUserToken adminUser) {
        logger.info("adminUser:{}", adminUser.toString());
        adminUserService.logout(adminUser.getAdminUserId());
        return ResultGenerator.genSuccessResult();
    }

    // 添加管理员,添加成功后返回true,否则返回false
    // @PostMapping("/adminUser/addNew")
    // @ApiOperation(value = "管理员添加", notes = "")
    // @RequestMapping(value = "/adminUser/addNew", method = RequestMethod.POST)
    // public Result addAdminUser(@RequestBody @Valid AdminAddNewDTO adminAddNewDTO) {
    //     String addResult = adminUserService.addAdminUser(adminAddNewDTO.getUserName(), adminAddNewDTO.getPassword(), adminAddNewDTO.getNickName());
    //     logger.info("add api,adminName={},addResult={}", adminAddNewDTO.getUserName(), addResult);
    //     //添加成功
    //     if (ServiceResultEnum.SUCCESS.getResult().equals(addResult)) {
    //         return ResultGenerator.genSuccessResult();
    //     }
    //     //添加失败
    //     return ResultGenerator.genFailResult(addResult);
    // }
    //
    // // 删除管理员,删除成功后返回true,否则返回false
    // @DeleteMapping("/adminUser/delete/{adminUserId}")
    // @ApiOperation(value = "管理员删除", notes = "")
    // @RequestMapping(value = "/adminUser/delete/{adminUserId}", method = RequestMethod.DELETE)
    // public Boolean deleteAdminUser(@PathVariable("adminUserId") Long adminUserId) {
    //     Boolean deleteResult = adminUserService.deleteAdminUser(adminUserId);
    //     logger.info("delete api,adminUserId={},deleteResult={}", adminUserId, deleteResult);
    //     //删除成功
    //     if (ServiceResultEnum.SUCCESS.getResult().equals(deleteResult)) {
    //         return true;
    //     }
    //     //删除失败
    //     return false;
    // }
    //
    // // 管理员列表
    // @RequestMapping(value = "/adminUser/list", method = RequestMethod.GET)
    // @ApiOperation(value = "管理员列表", notes = "")
    // public Result list(@RequestParam(required = false) @ApiParam(value = "页码") Integer pageNumber,
    //                    @RequestParam(required = false) @ApiParam(value = "每页条数") Integer pageSize,
    //                    @RequestParam(required = false) @ApiParam(value = "管理员状态") Integer lockStatus) {
    //     if (pageNumber == null || pageNumber < 1 || pageSize == null || pageSize < 10) {
    //         return ResultGenerator.genFailResult("参数异常！");
    //     }
    //     Map params = new HashMap(8);
    //     params.put("page", pageNumber);
    //     params.put("limit", pageSize);
    //     if (lockStatus != null) {
    //         params.put("orderStatus", lockStatus);
    //     }
    //     PageQueryUtil pageUtil = new PageQueryUtil(params);
    //     PageResult pageResult = adminUserService.getAdminUsersPage(pageUtil);
    //     if (pageResult != null && pageResult.getList() != null && pageResult.getList().size() > 0) {
    //         Result result = ResultGenerator.genSuccessResult();
    //         result.setData(pageResult);
    //         return result;
    //     }
    //     return ResultGenerator.genFailResult("暂无数据");
    // }

    // 添加管理员,添加成功后返回true,否则返回false
    // @ApiOperation("添加管理员")
    // @RequestMapping("/adminUser/addNew")
    // public JsonResult<Void> AddNew(@RequestBody @Valid AdminAddNewDTO adminAddNewDTO) {
    //     logger.debug("开始处理【添加管理员】的请求，参数：{}", adminAddNewDTO);
    //     adminUserService.addNew(adminAddNewDTO);
    //     return JsonResult.ok();
    // }
    //
    // // 删除管理员,删除成功后返回true,否则返回false
    // @ApiOperation("根据id删除管理员")
    // @ApiImplicitParam(name = "adminUserId", value = "管理员id", required = true, dataType = "long")
    // @PostMapping("/adminUser/{adminUserId:[0-9]+}/delete")
    // public JsonResult<Void> delete(@Range(min = 1, message = "删除管理员失败，参数错误")
    //                                @PathVariable Long adminUserId) {
    //     logger.debug("开始处理【删除管理员】的请求，参数：{}", adminUserId);
    //     adminUserService.delete(adminUserId);
    //     return JsonResult.ok();
    // }
    //
    // // 查询管理员列表
    // @ApiOperation("查询管理员列表")
    // @GetMapping("/adminUser/list")
    // public JsonResult<List<AdminVO>> list() {
    //     logger.debug("开始处理【查询管理员列表】的请求，无参数");
    //     List<AdminVO> list = adminUserService.list();
    //     return JsonResult.ok(list);
    // }
}
